package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApArticleSearchService;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.UserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ApArticleSearchService {


    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * ES文章分页搜索
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        log.info("【ES文章分页查询】---begin");
        log.info("【查询参数UserSearchDto】:{}",dto);
        //1.检验参数
        if(dto==null || dto.getSearchWords() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //异步调用保存搜索记录
        Integer user = UserThreadLocalUtil.getUser();
        if(user!=null && dto.getFromIndex()==0){ //关键字搜索只有第一次加载才保存
            log.info("【异步调用搜索记录】");
            apUserSearchService.insert(dto.getSearchWords(),user);
        }


        //2.设置查询条件
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //布尔查询
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //关键字的分词之后查询
        QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords())
                .field("title")
                .field("content")
                .defaultOperator(Operator.OR); //设置默认的逻辑运算符为 OR，表示查询时 title 或 content 中包含关键字即可

        boolQueryBuilder.must(queryStringQueryBuilder);
        //查询小于mindate的数据
//        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime());
//        boolQueryBuilder.filter(rangeQueryBuilder);
        //构建分页查询
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(dto.getPageSize());
        //发布时间倒叙排序
        searchSourceBuilder.sort("publishTime", SortOrder.DESC);

        //高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        searchSourceBuilder.highlighter(highlightBuilder);

        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //封装返回结果
        List<Map> list = new ArrayList<>();
        //SearchHit 是 Elasticsearch 查询结果中的一个对象，表示一个匹配的文档
        //获取查询结果
        SearchHit[] searchHits = searchResponse.getHits().getHits();
        for (SearchHit searchHit : searchHits) {
            String jsonResult = searchHit.getSourceAsString();//返回结果为json字符串
            Map map = JSON.parseObject(jsonResult,Map.class); //将json字符串转为map形式
            if(searchHit.getHighlightFields()!=null && searchHit.getHighlightFields().size()>0){
                Text[] texts = searchHit.getHighlightFields().get("title").getFragments(); //获取标题高亮片段
                log.info("标题高亮片段:{}", Arrays.toString(texts));
                String title = StringUtils.join(texts);
                map.put("h_title",title);
            }else{
                map.put("h_title",map.get("title"));
            }
            list.add(map);
        }
        log.info("【返回结果】:{}",list);
        log.info("【ES文章分页查询】---end");
        return ResponseResult.okResult(list);
    }
}
